{extend name="common/plugin_layout" /}
{block name="title"}{$plugin.title} - {:config_get('title')}{/block}
{block name="main"}
<style>
.btn-block {
	white-space:normal;
}
.btn-active {background-color: #1c2b46;color: #fff;}
</style>
<div class="container-xl" id="app">
<div class="col-sm-12 col-md-10 col-xl-9 center-block">
    <div class="card card-preview">
        <div class="card-inner mt-3">
            <div class="nya-title nk-ibx-action-item progress-rating">
                <span class="nk-menu-text font-weight-bold">QQ百度高速图床</span>
            </div>
            <div class="form-group">
                <label class="form-label" for="input">选择图床接口：</label>
                <div class="form-control-wrap">
                    <div class="custom-control custom-radio mr-3 mt-1" v-for="(item,index) in apitypes" :key="index">
                        <input type="radio" class="custom-control-input" v-model="set.apitype" name="set.apitype" :id="item.key" :value="item.key">
                        <label class="custom-control-label" :for="item.key">{{item.title}}</label>
                    </div>
                </div>
            </div>
            <div class="progress progress-lg mt-2 mb-1">
                <div class="progress-bar progress-bar-striped progress-bar-animated" v-bind:style="{ width: progress + '%' }">{{progress}}%</div>
            </div>
            <div class="form-group">
                <div class="text-center pt-5 pb-5 btn btn-lg btn-block btn-outline-light mb-4 d-block" id="fileInput">
                    <div class="preview-icon-wrap"><em class="ni ni-upload"></em></div><span>拖拽文件到这里或者点击选择文件</span>
                    <input type="file" id="file" accept="image/*" multiple="multiple" style="opacity: 0;position: absolute;cursor: pointer;width: 100%;height: 100%;left: 0;top: 0;" @change="selectFile">
                </div>
            </div>
            
            <div class="form-group">
                <div class="btn-group">
                    <button v-for="v in set.output_types.items" class="btn btn-outline-dark btn-sm"
                            :class="{'btn-active':set.output_types.current===v.key}"
                            @click="set.output_types.current=v.key"
                    >
                        {{v.title}}
                    </button>
                </div>
                <div class="form-control-wrap">
                    <textarea class="form-control" id="output" v-model="result" rows="8" placeholder="这里显示上传的结果"></textarea>
                </div>
                <div class="text-center"><button class="btn btn-sm btn-outline-light" @click="copy"><em class="icon ni ni-copy"></em>点此复制</button>&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-sm btn-outline-light" @click="reset"><em class="icon ni ni-reload"></em>清空</button></div>
            </div>
        </div>
    </div>
    <div class="card card-preview">
        <div class="card-inner">
            <h6><em class="icon ni ni-info"></em> 工具说明</h6>
            <div class="accordion-inner">
                <p>文件格式支持：jpg,jpeg,png,gif,webp，大小不能超过10M</p>
                <p>QQ(1)：图片域名yzf.qq.com，原图无压缩</p>
                <p>文库：图片域名wkphoto.cdn.bcebos.com，原图无压缩</p>
                <p>百家号：图片域名pic.rmb.bdstatic.com，原图无压缩</p>
                <p>aichat：图片域名static.aichat.net，原图无压缩</p>
                <p>uniCloud：<a href="/unicloud">点此跳转</a></p>
            </div>
        </div>
    </div>
</div>
</div>
{/block}
{block name="script"}
<script src="{$cdn_cdnjs}vue/2.6.14/vue.min.js"></script>
<script src="{$cdn_cdnjs}jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            apitypes: [
                {
                    title: 'QQ(1)',
                    key: 'qqyzf'
                },
                {
                    title: '文库',
                    key: 'wenku'
                },
                {
                    title: '百家号',
                    key: 'baijiahao'
                },
                {
                    title: 'aichat',
                    key: 'aichat'
                },
            ],
            set: {
                output_types: {
                    current: 'URL',
                    items: [
                        {
                            title: 'URL',
                            key: 'URL',
                            template: '#url#',
                        },
                        {
                            title: 'HTML',
                            key: 'HTML',
                            template: '<img src="#url#"/>',
                        },
                        {
                            title: 'BBCode',
                            key: 'BBCode',
                            template: '[img]#url#[/img]',
                        },
                        {
                            title: 'Markdown',
                            key: 'Markdown',
                            template: '![](#url#)',
                        },
                        {
                            title: 'Markdown&Link',
                            key: 'MarkdownWithLink',
                            template: '[![](#url#)](#url#)',
                        },
                    ]
                },
                output: [],
                apitype: 'qqyzf',
            },
            progress: 0,
            urls: {},
            result: '',
        },
        mounted() {
            if($.cookie('imghosting_apitype')){
                this.set.apitype = $.cookie('imghosting_apitype')
            }
        },
        watch: {
            'set.apitype'(newVal) {
                $.cookie('imghosting_apitype',newVal)
            },
            'set.output'(newVal) {
                let list = {}
                for (item of this.set.output_types.items) {
                    let arr = []
                    for (const v of newVal) {
                        arr.push(item.template.replaceAll('#url#', v))
                    }
                    list[item.key] = arr;
                }
                this.urls = list
            },
            'urls'(newVal) {
                this.result = newVal[this.set.output_types.current].join('\n')
            },
            'set.output_types.current'(newVal) {
                this.result = this.urls[newVal] ? this.urls[newVal].join('\n') : '';
            }
        },
        methods: {
            async uploadFile(file, total, id){
                var that = this;
                return new Promise((resolve, reject) => {
                    if(file.size > 10485760){
                        reject('上传失败！文件超过10M');return;
                    }
                    var data = new FormData();
                    data.append('file', file);
                    data.append('apitype', that.set.apitype);
                    $.ajax({
                        type : "POST",
                        url : "/api/{$plugin.alias}/upload",
                        data : data,
                        processData: false,
                        contentType: false,
                        dataType : 'json',
                        success : function(data) {
                            if(data.code == 0){
                                resolve(data.data.url);
                            }else{
                                reject(data.msg);
                            }
                        },
                        error : function(){
                            reject('上传失败！接口错误');
                        },
                        xhr: function() {
                            var xhr = new XMLHttpRequest();
                            xhr.upload.addEventListener('progress', function (e) {
                                //console.log(e);
                                progressRate = Math.round(e.loaded / e.total / total * 100 + (id-1) / total * 100);
                                that.progress = progressRate;
                            })
                            return xhr;
                        }
                    });
                })
            },
            async selectFile(e) {
                var total = e.target.files.length;
                if(total == 0) return;
                this.progress = 0;
                let loading = layer.msg('正在上传中', {icon: 16,shade: 0.1,time: 0});
                var error = '';
                var i = 1;
                for (const file of e.target.files) {
                    await this.uploadFile(file, total, i++).then(res => {
                        this.set.output.push(res)
                    }, res => {
                        error += res + "<br/>";
                    })
                }
                $("#file").val('');
                layer.close(loading);
                if(error){
                    layer.alert(error, {icon: 2});
                }
            },
            copy(){
                if(!this.result) return;
                $("#output").select();
                document.execCommand("Copy");
                layer.msg('复制成功', {icon:1, time:600})
            },
            reset(){
                this.set.output = [];
                this.progress = 0;
            }
        },
    })
</script>
{/block}